module.exports = (EdtApi) => {
    "use strict";
    let chatId = "", count = 0, badges, _theme = "light";
    function setTheme(theme = "light") {
        localStorage.setItem("igt", theme);
        let classList = document.querySelector("html")?.classList;
        if (!classList) return;
        classList.remove("dark" == theme ? "_aa4c" : "_aa4d");
        classList.remove("dark" == theme ? "__fb-light-mode" : "__fb-dark-mode");
        classList.add("dark" == theme ? "__fb-dark-mode" : "__fb-light-mode");
        classList.add("dark" == theme ? "_aa4d" : "_aa4c");
    }
    window.addEventListener('load', () => {
        setTheme(localStorage.getItem("edt-theme") || "light");
    });
    function isGroup() {
        let el = document.querySelector(
            'main[role="main"] .x9f619.x1n2onr6.x1ja2u2z.x78zum5.xdt5ytf.x2lah0s.x193iq5w.xeuugli.xsyo7zv.x16hj40l.x10b6aqq.x1yrsyyn'
        );
        return el?.querySelectorAll("img")?.length > 1;
    }
    async function getChatId(times = 0) {
        let url = window.location.href;
        const regex = /\/t\/(\d+)\/?/;
        const match = regex.exec(url);
        let id = "";
        try {
            if (match) id = match[1];
        } catch (error) {
            console.log('获取对话id失败', error)
        }
        if (id && id != chatId) return id;
        await EdtApi.sleep(50);
        if (times > 10) return id;
        times++;
        return getChatId(times);
    }
    return {
        config: {
            friendList: 'div[aria-label="Chats"][role="list"]',
            chat: 'div[aria-label][role="main"]',
            input: 'main[role="main"] div.x1n2onr6 div[role="textbox"]',
            msgBox: 'main[role="main"] div[data-pagelet="IGDOpenMessageList"] div[role="grid"],main[role="main"] div[role="none"] div[role="grid"],div[role="main"] div[role="none"] div[role="grid"]',
            inMsg: 'div[data-scope="messages_table"][role="gridcell"] div.html-div.x5od304.x11ucwad.xgtuqic>span[dir="auto"]:not(.trans-inited)',
            outMsg: 'div[data-scope="messages_table"][role="gridcell"] div.html-div.xp5s12f.x155c047>span[dir="auto"]:not(.trans-inited)',
            sendBtn: "div.x1i10hfl.xjqpnuy.xa49m3k.xqeqjp1.x2hbi6w.xdl72j9.x2lah0s.xe8uvvx.xdj266r.xat24cr.x1mh8g0r.x2lwn1j.xeuugli.x1hl2dhg.xggy1nq.x1ja2u2z.x1t137rt.x1q0g3np.x1lku1pv.x1a2a7pz.x6s0dn4.xjyslct.x1ejq31n.xd10rxx.x1sy0etr.x17r0tee.x9f619.x1ypdohk.x1f6kntn.xwhw2v2.xl56j7k.x17ydfre.x2b8uid.xlyipyv.x87ps6o.x14atkfc.xcdnw81.x1i0vuye.xjbqb8w.xm3z3ea.x1x8b98j.x131883w.x16mih1h.x972fbf.xcfux6l.x1qhh985.xm0m39n.xt0psk2.xt7dq6l.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x1n2onr6.x1n5bzlp.x173jzuc.x1yc6y37.xfs2ol5",
            setting: 'div.x6s0dn4.x78zum5.x1gg8mnh.x1pi30zi.xlu9dua>div.x9f619.xjbqb8w.x78zum5.x168nmei.x13lgxp2.x5pf9jr.xo71vjh.x1i64zmx.xw3qccf.x1uhb9sk.x1plvlek.xryxfnj.x1iyjqo2.x2lwn1j.xeuugli.xdt5ytf.xqjyukv.x1qjc9v5.x1oa3qoh.x1nhvcw1',
            tips: {
                in: 'main[role="main"] div.x9f619.x1n2onr6.x1ja2u2z.x78zum5.xdt5ytf.x193iq5w.xeuugli.x1r8uery.x1iyjqo2.xs83m0k.xsyo7zv.x16hj40l.x10b6aqq.x1yrsyyn',
                out: 'div.x1qjc9v5.x1yvgwvq.x1dqoszc.x1ixjvfu.xhk4uv.x1ke7ulo.x3jqge.x1i7howy.x4y8mfe.x13fuv20.xu3j5b3.x1q0q8m5.x26u7qi.x178xt8z.xm81vs4.xso031l.xy80clv.x78zum5.xdt5ytf.xw7yly9.xktsk01.x1yztbdb.x1d52u69'
            },
            crm: {
                // listener: '#LeftColumn-main',
                top: 'div[aria-label][role="main"] div.x1r8uery>a[role="link"]',
                left: ""
            },
            placeholder: {
                selector: "div.x1n2onr6 div.xi81zsa.x6ikm8r.x10wlt62.x47corl.x10l6tqk.x17qophe.xlyipyv.x13vifvy.x87ps6o.xuxw1ft.xh8yej3",
                delay: 200,
                update: true
            },
            extra: {//其他会触发对话框变动的情况处理
                selector: 'div[role="dialog"] div.x9f619.xjbqb8w.x78zum5.x168nmei.x13lgxp2.x5pf9jr.xo71vjh.xw7yly9.xktsk01.x1yztbdb.x1d52u69>div[role="button"],main header section div[role="button"]',
                level: 10,
                delay: 800,
            },
            autoCount: 20
        },
        init() {
            // console.log("init:::");
            document.addEventListener('contextmenu', e => {
                let target = e.target;
                let a = EdtApi.closest(target, 'a[role="link"]')
                if (a) {
                    console.log(a.href);
                    navigator.clipboard.writeText(a.href).then(() => {
                        // console.log('文本已成功复制到剪贴板');
                        EdtApi.sendToHost("show-message", { type: "success", options: { message: "链接复制成功。" } });
                    }).catch(err => {
                        console.error('无法复制到剪贴板', err);
                        EdtApi.sendToHost("show-message", { type: "error", options: { message: "链接复制失败！" } });
                    });
                } else if ("IMG" == target.nodeName && EdtApi.closest(target, 'img[crossorigin="anonymous"]')) {
                    let menu = document.getElementById("edt-menu");
                    if (menu) {
                        if (menu.querySelector('div[command="copy-page-url"]')) return;
                        let btn = document.createElement("div");
                        btn.className = "edt-menu-item";
                        btn.setAttribute("command", "copy-page-url");
                        btn.innerHTML = "复制页面链接";
                        menu.prepend(btn);
                        btn.onclick = () => {
                            // console.log("复制页面链接", location.href);
                            navigator.clipboard.writeText(location.href).then(() => {
                                // console.log('文本已成功复制到剪贴板');
                                EdtApi.sendToHost("show-message", { type: "success", options: { message: "链接复制成功。" } });
                            }).catch(err => {
                                console.error('无法复制到剪贴板', err);
                                EdtApi.sendToHost("show-message", { type: "error", options: { message: "链接复制失败！" } });
                            });
                        }
                    }
                }
            });
        },
        setTheme({ theme }) {
            localStorage.setItem("edt-theme", theme);
            setTheme(theme);
        },
        getUnread() {
            badges = document.querySelector('a[href^="/direct/inbox/"] .xwmz7sl.xo1l8bm.x1ncwhqj.xyqdw3p.x1mpkggp.xg8j3zb.x1t2a60a');
            count = badges ? EdtApi.safeParseInt(badges.textContent) : 0;
            return count;
        },
        getChatInfo() {
            return new Promise(async (resolve) => {
                chatId = await getChatId();
                resolve({ id: chatId, isGroup: isGroup() });
            });
        },
        getChatTitle(chatEl = document) {
            let titleEl = chatEl.querySelector('main[role="main"] span.x1lliihq.x193iq5w.x6ikm8r.x10wlt62.xlyipyv.xuxw1ft');
            return titleEl?.textContent || "";
        },
        getText(msgBox) {
            if (!msgBox) return "";
            let msgSpan = msgBox.querySelector("div.html-div");
            return msgSpan?.textContent || "";
        },
        getIptMsg(inputEl) {
            if (!inputEl) return "";
            let value = "";
            try {
                let node = inputEl.querySelector("p.xat24cr.xdj266r");
                node?.childNodes?.length > 0 &&
                    node.childNodes.forEach((item) => {
                        if (item.tagName === "BR") {
                            value += "\n";
                        } else {
                            value += item.textContent;
                        }
                    });
            } catch (error) {
                console.error(error);
            }
            return value;
        },
        preventSend({ chatEl }) {//处理语音发送
            let audioEl = chatEl.querySelector(`${this.config.tips.out} div.x4k7w5x.x1h91t0o.x1beo9mf.xaigb6o.x12ejxvf.x3igimt.xarpa2k.xedcshv.x1lytzrv.x1t2pt76.x7ja8zs.x1n2onr6.x1qrby5j.x1jfb8zj`);
            return !audioEl;
        },
        getUserInfo() {
            try {
                let userEl = document.querySelector('div.x1iyjqo2.xh8yej3 div.x1n2onr6>span[aria-describedby=":ra:"] a[role="link"][href]');
                let avatar = "";
                let userName = "";
                let account = " ";
                if (userEl) {
                    userName = userEl.getAttribute("href");
                    if (userName) userName = userName.replace(/\//g, "");
                    avatar = userEl.querySelector("img")?.getAttribute("src");
                }
                return {
                    avatar,
                    userName,
                    account,
                    toDataUrl: true
                }
            } catch (error) {
                return null;
            }
        }
    };
};